<?php

namespace app\api\controller;

use addons\third\library\Service;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\logic\AddressLogic;
use app\common\validate\UserValidate;
use fast\Http;
use fast\Random;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'login_wx', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }





    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        (new AddressLogic())->areaChange();
        (new UserValidate())->goCheck();
        $data = $this->request->post();
        $data['is_bind'] = 1;
        $user = new \app\common\model\User();

        $user->allowField(true)->save($data,['id' => UID]);
        $this->success();
    }



    /**
     * 修改手机号
     *
     * @param string $email   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->param('mobile');
        $captcha = $this->request->param('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }


    /**
     * 小程序登录
     */
    public function login_wx()
    {
        $config = config('site.wxapp');
        $code = $this->request->post("code", '');
        $rawData = $this->request->post("rawData", '', 'trim');
        $parent_id = input('parent_id/d', 0);
        if (!$code || !$rawData) {
            $this->error("参数不正确");
        }
        $userInfo = (array)json_decode($rawData, true);
        $params = [
            'appid'      => $config['wxappid'],
            'secret'     => $config['wxappsecret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                $platform = 'wxapp';
                $result = [
                    'openid'        => $json['openid'],
                    'userinfo'      => [
                        'nickname' => $userInfo['nickName'],
                    ],
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                ];
                $extend = ['parent_id'=> $parent_id, 'gender' => $userInfo['gender'], 'nickname' => $userInfo['nickName'], 'avatar' => $userInfo['avatarUrl']];
                $ret = Service::connect($platform, $result, $extend, 10*24*3600);
                if ($ret) {
                    $auth = Auth::instance();
                    $this->success("登录成功", ['userInfo' => $this->userinfo()]);
                } else {
                    $this->error("连接失败");
                }
            }
        }

        $this->error('登陆失败');

    }




    private function userinfo() {
        $user = $this->auth->getUser();
        $userinfo = $this->auth->getUserinfo();

        $userinfo['real_name'] = $user['real_name'];
        $userinfo['gender'] = $user['gender'];
        $userinfo['birthday'] = $user['birthday'];
        $userinfo['nation'] = $user['nation'];
        $userinfo['school'] = $user['school'];
        $userinfo['duty'] = $user['duty'];
        $userinfo['grade'] = $user['grade'];
        $userinfo['mobile'] = $user['mobile'];
        $userinfo['is_bind'] = $user['is_bind'];

        $userinfo['config'] = [
          'concat_phone' => config('site.concat_phone')
        ];
        return $userinfo;
    }


    public function getUserinfo() {
        $this->success('用户信息', $this->userinfo());
    }
}
